#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : light-edit
@File : port_scan.py
@Author : Yj
@Time : 2025/9/9
@脚本说明 : 端口扫描模块，扫描指定主机的端口范围
"""
import socket
import threading
import queue


def scan_port(host, port, result_queue):
    """尝试连接指定主机的端口，判断是否开放"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.2)  # 设置超时时间为0.5秒
    try:
        result = sock.connect_ex((host, port))
        if result == 0:  # 返回0表示端口开放
            result_queue.put(port)
    except (socket.gaierror, socket.error):
        pass
    finally:
        sock.close()


def port_scanner(host, start_port, end_port):
    print(f"正在扫描 {host} 的端口 {start_port}-{end_port}...")
    open_ports = []
    result_queue = queue.Queue()
    threads = []

    # 创建线程扫描每个端口
    for port in range(start_port, end_port + 1):
        t = threading.Thread(target=scan_port, args=(host, port, result_queue))
        threads.append(t)
        t.start()

    # 等待所有线程完成
    for t in threads:
        t.join()

    # 从队列中获取开放端口
    while not result_queue.empty():
        open_ports.append(result_queue.get())

    # 按端口号排序
    open_ports.sort()

    # 输出结果
    if open_ports:
        print("扫描结果:")
        for port in open_ports:
            print(f"端口 {port} 开放")
    else:
        print("未发现开放端口。")
